﻿namespace MefContrib.Models.Provider.Definitions.Configurable
{
    using System;
    using System.Collections.ObjectModel;
    using System.Configuration;
    using System.Diagnostics;

    public class PartCatalogConfigurationExportCollection : ConfigurationElementCollection
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PartCatalogConfigurationExportCollection"/>
        /// </summary>
        public PartCatalogConfigurationExportCollection()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override ConfigurationElement CreateNewElement()
        {
            return new PartCatalogConfigurationExport();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <value></value>
        public override ConfigurationElementCollectionType CollectionType
        {
            [DebuggerStepThrough]
            get { return ConfigurationElementCollectionType.BasicMap; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <value></value>
        protected override string ElementName
        {
            [DebuggerStepThrough]
            get { return "export"; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        protected override object GetElementKey(ConfigurationElement element)
        {
            var part = element as PartCatalogConfigurationExport;

            if (part != null)
            {
                return part.Member;
            }

            // TODO: Write exception message.
            throw new InvalidOperationException();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public Collection<ExportDescription> AsCollection()
        {
            var exports = new Collection<ExportDescription>();

            foreach (PartCatalogConfigurationExport export in this)
            {
                exports.Add(
                    new ExportDescription
                    {
                        ContractName = export.ContractName,
                        ContractType = Type.GetType(export.ContractType),
                        MemberName = export.Member,
                        Metadata = export.Metadata.AsDictionary()
                    }
                );
            }

            return exports;
        }
    }
}